#! /usr/bin/env python3
import numpy as np
from flask import Flask, Response, request, render_template_string
import cv2

app = Flask(__name__)

latest_frame=None

# @app.route("/")
# def hello():
#     return "Hello World!"


def generate_frames():
    cap = cv2.VideoCapture(0)  # 或者使用0来从摄像头读取
    while True:
        success, frame = cap.read()
        if not success:
            print('cap_break')
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

def generate_frames1():
    global latest_frame
    while True:
        # global latest_frame
        if latest_frame is not None:

            # 将图像编码为 JPEG 格式
            ret, buffer = cv2.imencode('.jpg', latest_frame)
            if ret:
                frame = buffer.tobytes()
                yield (b'--frame\r\n'
                       b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')


@app.route('/upload_video', methods=['POST'])
def upload_video():
    global latest_frame
    # 读取 POST 请求中的视频流
    video_stream = request.data
    # 将字节流转换为图像
    nparr = np.frombuffer(video_stream, np.uint8)
    frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    if frame is not None:
        latest_frame = frame
    return 'Frame received successfully!', 200


@app.route('/video_feed')
def video_feed():
    return Response(generate_frames1(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
    # if request.method=='POST':
    #     return Response(generate_frames1(),
    #                     mimetype='multipart/x-mixed-replace; boundary=frame')
    # else:
    #
    #     return Response(generate_frames(),
    #                     mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/')
def index():
    return render_template_string('''
    <html>
    <body>
        <h1>Video Feed</h1>
        <img src="{{ url_for('video_feed') }}" style="width: 640px; height: 480px;">
    </body>
    </html>
    ''')


if __name__ == "__main__":
    app.run(host='0.0.0.0')

#
# from flask import Flask
# app = Flask(__name__)
#
# @app.route("/")
# def hello():
#     return "Hello World!"
#
# if __name__ == "__main__":
#     app.run(port=6666)
# #
